/*
 * @Author: Haochen
 * @Date: 2021-11-23 11:43:36
 * @LastEditTime: 2021-11-26 11:06:35
 * @FilePath: \front\src\js\common.js
 */

import $ from './jquery-3.6.0.min.js';

export function getPromise(url, type = 'get', data = {}) {
  return new Promise(function (resolve, reject) {
    $.ajax({
      type: type,
      url: url,
      traditional: true, //防止深度序列化
      success: function ({ code, data, message }) {
        resolve({ code, data, message });
      },
      data,
      // 设置参数，防止jQuery自动处理,以便将文件数据原封不动的传给后端处理
      // contentType: false,
      // processData: false,
      // cache: false,
    });
  });
}

export function getPromise1(url, type = 'get', data = {}) {
  return new Promise(function (resolve, reject) {
    $.ajax({
      type: type,
      url: url,
      traditional: true, //防止深度序列化
      success: function ({ message, code, token, user }) {
        resolve({ message, code, token, user });
      },
      data,
      // 设置参数，防止jQuery自动处理,以便将文件数据原封不动的传给后端处理
      // contentType: false,
      // processData: false,
      // cache: false,
    });
  });
}

export function getPromiseForUploadImg(data = {}) {
  return new Promise(function (resolve, reject) {
    $.ajax({
      type: 'post',
      url: '/upload/image',

      success: function ({ message, data, code }) {
        resolve({ message, data, code });
      },
      data,
      // 设置参数，防止jQuery自动处理,以便将文件数据原封不动的传给后端处理
      contentType: false,
      processData: false,
      cache: false,
    });
  });
}

export function getPromiseAuthBy(url, token, type = 'get', data) {
  return new Promise(function (resolve, reject) {
    $.ajax({
      type,
      url,
      success: function ({ code, user, message }) {
        resolve({ code, user, message });
      },
      headers: {
        Authorization: token,
      },
      error: function () {
        localStorage.token = '';

        alert('已过登录期，请重新登录');

        location.href = './login.html';
      },
      data,
    });
  });
}

export async function backToIndex() {
  $('.head-left').click(function () {
    location.href = '../html/index.html';
  });

  const users = JSON.parse(localStorage.getItem('users'));

  const userId = users.find((user) => user.status === 'online')._id;

  const token = localStorage.token;

  const { code, user, message } = await getPromiseAuthBy(
    '/students/:' + userId,
    token,
    'get',
    {}
  );

  $('.user img').attr('src', `${user[0].avatar}`);
  $('.user h3').text(`${user[0].name}`);
}
